import { createRouter, createWebHistory } from 'vue-router'
// import HomeView from '../views/HomeView.vue'
import menuView from '../views/menu/menuView.vue'
import loginView from '@/views/login/loginView.vue'
import SignView from '@/views/login/SignView.vue'
import { sessionGet } from '@/utils/sessionStorage'
import { sessionClear } from '@/utils/sessionStorage'
import homeRouter from './modules/home'
import booksRouter from './modules/books'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'index',
      component: menuView,
      redirect: '/home',
      children: [homeRouter, booksRouter]
    },
    {
      path: '/login',
      name: 'login',
      component: loginView
    },
    {
      path: '/sign',
      name: 'sign',
      component: SignView
    },

  ]
})

router.beforeEach((to, from, next) => {
  if (sessionGet('token')) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }

  } else {
    if (to.name === 'sign') return next()
    if (to.name === 'login') {
      sessionClear()
      return next()
    }
    next('/login')

  }
})
export default router

